package com.hupu.jrs.util

import android.app.Activity
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.support.v4.app.NotificationCompat
import android.text.Html
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.fastjson.JSON
import com.hupu.jrs.R
import com.hupu.jrs.bean.UpdateInfo
import com.hupu.jrs.ui.main.MainActivity
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.yalantis.phoenix.util.Logger
import java.io.File
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.schedulers.Schedulers

/**
 * Created by sll on 2015/10/8.
 */
class UpdateAgent(private val mOkHttpHelper: OkHttpHelper, private val mActivity: Activity) {

    private var mNotifyManager: NotificationManager? = null
    private var mBuilder: NotificationCompat.Builder? = null
    private var destinationUri: Uri? = null

    private val listener = object : FileDownloadListener() {
        override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

        }

        override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
            val progress = soFarBytes * 100 / totalBytes
            val content = String.format("正在下载:%1\$d%%", progress)
            mBuilder!!.setContentText(content).setProgress(totalBytes, soFarBytes, false)
            val pendingintent = PendingIntent.getActivity(mActivity, 0, Intent(mActivity, MainActivity::class.java),
                    PendingIntent.FLAG_CANCEL_CURRENT)
            mBuilder!!.setContentIntent(pendingintent)
            mNotifyManager!!.notify(0, mBuilder!!.build())
        }

        override fun blockComplete(task: BaseDownloadTask) {

        }

        override fun completed(task: BaseDownloadTask) {
            val installAPKIntent = Intent(Intent.ACTION_VIEW)
            //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
            FileUtil.chmod("777", destinationUri!!.path)
            installAPKIntent.setDataAndType(Uri.parse("file://" + destinationUri!!.path),
                    "application/vnd.android.package-archive")
            val pendingIntent = PendingIntent.getActivity(mActivity, 0, installAPKIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT)
            mBuilder!!.setContentIntent(pendingIntent)
            installAPKIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            mActivity.startActivity(installAPKIntent)
            // 下载完成
            mBuilder!!.setContentText("下载成功（点击安装）").setProgress(0, 0, false)
            mNotifyManager!!.notify(0, mBuilder!!.build())
        }

        override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

        }

        override fun error(task: BaseDownloadTask, e: Throwable) {
            Logger.d("error:" + e.message)
        }

        override fun warn(task: BaseDownloadTask) {

        }
    }

    fun checkUpdate() {
        this.checkUpdate(true)
    }

    fun checkUpdate(show: Boolean) {
        mNotifyManager = mActivity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        mBuilder = NotificationCompat.Builder(mActivity)
        Observable.create<UpdateInfo> { subscriber ->
            try {
                val result = mOkHttpHelper.getStringFromServer(Constants.UPDATE_URL)
                subscriber.onNext(JSON.parseObject<UpdateInfo>(result, UpdateInfo::class.java))
                subscriber.onCompleted()
            } catch (e: Exception) {
                subscriber.onError(e)
            }
        }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ updateInfo ->
                    if (updateInfo != null) {
                        checkUpdateFinished(updateInfo, show)
                        if (updateInfo!!.extra != null) {
                            SettingPrefUtil.setNeedExam(mActivity, updateInfo!!.extra.needExam === 1)
                        }
                        SettingPrefUtil.setHuPuSign(mActivity, updateInfo!!.hupuSign)
                    }
                }) { throwable -> throwable.printStackTrace() }
    }

    private fun checkUpdateFinished(updateInfo: UpdateInfo?, show: Boolean) {
        if (updateInfo!!.versionCode > BuildConfig.VERSION_CODE && SettingPrefUtil.getAutoUpdate(
                mActivity) && show) {
            showUpdateDialog(updateInfo)
        }
    }

    private fun showUpdateDialog(updateInfo: UpdateInfo?) {
        if (updateInfo != null) {
            val builder = MaterialDialog.Builder(mActivity).title("升级新版本")
            builder.positiveText("立刻升级").negativeText("取消").content(Html.fromHtml(updateInfo!!.updateInfo))
            builder.callback(object : MaterialDialog.ButtonCallback() {
                override fun onPositive(dialog: MaterialDialog?) {
                    try {
                        val url = updateInfo!!.updateUrl
                        mBuilder!!.setContentTitle(mActivity.getString(R.string.app_name) + "正在更新")
                                .setAutoCancel(true)
                                .setSmallIcon(mActivity.packageManager
                                        .getPackageInfo(mActivity.packageName, 0).applicationInfo.icon)
                        destinationUri = Uri.parse(SDCARD_ROOT + File.separator + FormatUtil.getFileNameFromUrl(url))
                        FileDownloader.getImpl()
                                .create(url)
                                .setPath(SDCARD_ROOT + File.separator + FormatUtil.getFileNameFromUrl(url))
                                .setListener(listener)
                                .start()
                        Toast.makeText(mActivity, "开始下载新版本，稍后会开始安装", Toast.LENGTH_SHORT).show()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }
            }).show()
        }
    }

    companion object {

        val SDCARD_ROOT = Environment.getExternalStorageDirectory().absolutePath + "/gzsll/hupu"
    }
}
